package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.admin.client.DataClient;
import com.ytjj.qmyx.admin.constants.RedisConstant;
import com.ytjj.qmyx.admin.dao.ChannelDao;
import com.ytjj.qmyx.admin.dao.SelectChannelDao;
import com.ytjj.qmyx.admin.dao.SelectExamDao;
import com.ytjj.qmyx.admin.eunm.PromotePlatformEnums;
import com.ytjj.qmyx.admin.eunm.PromotersEnums;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.request.ChannelAddRequest;
import com.ytjj.qmyx.admin.model.request.ChannelRequest;
import com.ytjj.qmyx.admin.model.request.PromotePlat;
import com.ytjj.qmyx.admin.model.vo.ChannelVO;
import com.ytjj.qmyx.admin.service.AdminService;
import com.ytjj.qmyx.admin.service.ChannelService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.model.Channel;
import com.ytjj.qmyx.mall.model.SelectExam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class ChannelServiceImpl implements ChannelService {

    @Resource
    private ChannelDao channelDao;

    @Resource
    private SelectChannelDao selectChannelDao;

    @Resource
    private SelectExamDao selectExamDao;

    @Autowired
    private MallClient mallClient;

    @Autowired
    private DataClient dataClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AdminService adminService;

    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

    @Value("${supply.api.shopId}")
    private String shopId;

    /**
     * jxy代运营账号id
     */
    @Value("${adminIddyx:268}")
    private Integer adminIdjxy;

    @Override
    public List<Channel> selectList() {
        String channel = null;
        String userId= UserUtil.getPrincipal();
        Admin admin = adminService.getAdminByEmail(userId);
        if (admin!=null && admin.getId().equals(adminIdjxy)){
            channel = "jxy-tt";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(userId) && "jxy02@lc.com".equals(userId)){
            channel = "ds-";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(userId) && "csb001@lc.com".equals(userId)){
            channel = "qw-";
        }
        return channelDao.selectList(channel);
    }

    @Override
    public CommonPage<Channel> getChannelList(ChannelRequest channelRequest) {
        String channel = null;
        String userId= UserUtil.getPrincipal();
        Admin admin = adminService.getAdminByEmail(userId);
        if (admin!=null && admin.getId().equals(adminIdjxy)){
            channel = "jxy-tt";
        }
        channelRequest.setChannel(channel);
        PageHelper.startPage(channelRequest.getPageNum(), channelRequest.getPageSize());
        List<Channel> pageList = channelDao.getChannelList(channelRequest);
        return CommonPage.restPage(pageList);
    }

    @Override
    public Integer insertChannel(Channel channel) {
        channel.setCreateTime(new Date());
        channel.setPid(0);
        if(StringUtils.isEmpty(channel.getChannel())) {
            throw new ApiException("渠道不能为空！");
        } else {
            // 验证是否存在该渠道数据
            if(channelDao.isExist(channel.getChannel()) > 0) {
                throw new ApiException("该渠道已存在，请勿重复添加！");
            }

            // 不存在该数据，执行增加操作
            String value = channel.getChannel();
            String str = value.substring(value.lastIndexOf("-") + 1);
            Integer num = Integer.parseInt(str) + 1;
            channel.setSerial(num);
        }
        Integer count = channelDao.insertChannel(channel);
        if(count > 0) {
            String realchannel=channel.getChannel();
            int pid=channel.getId();
            //同步channel_old信息
            channel.setChannel(realchannel + "-old");
            channel.setPid(pid);
            channelDao.insertChannel(channel);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addChannel(ChannelAddRequest addRequest) {
        // 数据验证
//        if(StringUtils.isEmpty(addRequest.getPromoters())) {
//            throw new ApiException("推广方不能为空！");
//        }
//        if(StringUtils.isEmpty(addRequest.getPlatList())) {
//            throw new ApiException("推广平台不能为空！");
//        }
//        if(StringUtils.isEmpty(addRequest.getRedirectUrl())) {
//            throw new ApiException("推广跳转链接不能为空！");
//        }
        if(!StringUtils.isEmpty(addRequest.getPlatList())) {
            this.getAutoChannel(addRequest.getPlatList(), addRequest.getPlatform(), addRequest.getPromoters(), addRequest.getRedirectUrl(), addRequest.getShortUrl(),addRequest.getDataUserId(),addRequest.getCoupon(),addRequest.getDomain());
        } else {
            this.getManualChannel(addRequest.getPlatform(), addRequest.getChannel(), addRequest.getRedirectUrl(), addRequest.getShortUrl(),addRequest.getDataUserId(),addRequest.getCoupon());
        }
        // 刷新平台缓存
        //mallClient.reflushCash();

        // 刷新渠道缓存
//        dataClient.refreshPathCode();
//
//        // 刷新渠道跳转路径缓存
//        List<ChannelVO> channels = channelDao.findChannel();
//        redisService.delete(RedisConstant.CHANNEL);
//        channels.stream().forEach(item -> {
//            redisService.add(RedisConstant.CHANNEL, item.getChannel(), item.getRedirectUrl());
//        });

    }


    public void getAutoChannel(List<PromotePlat> platList, String platform, String promoterList, String redirectUrls, String shortUrl, Integer dataUserId, BigDecimal coupon,String domain) {
        for(PromotePlat plat : platList) {
            // 推广链接数量
            for(int i = 0; i< plat.getPlatNum(); i++) {
                Channel channel = new Channel();

                channel.setCreateTime(new Date());
                channel.setPid(0);
                channel.setSort(1);
                channel.setPlatform(platform.replaceAll(" ", ""));
                channel.setDataUserId(dataUserId);
                channel.setCoupon(coupon);
                // 推广方
                String promoters = promoterList.replaceAll(" ", "");

                // 渠道 = 推广方 + 推广平台 + 序列号(上一序列自增+1)
                String head = promoters + "-" + plat.getPlatName() + "-";
                Integer serial = channelDao.getSerial(head);
                String channelValue = "";
                if(serial == null) {
                    channelValue = head + "01";
                    serial=1;
                } else {
                    if(serial < 10) {
                        channelValue = head + "0" + serial;
                    } else {
                        channelValue = head + serial;
                    }
                }
                //检查是否存在渠道号
                while(channelDao.isExist(channelValue)>0){
                    serial+=1;
                    if(serial < 10) {
                        channelValue = head + "0" + serial;
                    } else {
                        channelValue = head + serial;
                    }
                }
                channel.setChannel(channelValue);
                String headDescr = Optional.ofNullable(PromotersEnums.getName(promoters)).orElse(promoters);
                String tailDescr = PromotePlatformEnums.getName(plat.getPlatName());
                channel.setChannelDesc(headDescr + "-" + tailDescr);

                channel.setChannelUserId(null);
                if(headDescr.equals("wei")) {
                    channel.setChannelUserId(4);
                }else if(headDescr.equals("guobao")||headDescr.equals("txg")) {
                    channel.setChannelUserId(7);
                }else if(headDescr.equals("jx")) {
                    channel.setChannelUserId(12);
                }else if(headDescr.equals("ht")) {
                    channel.setChannelUserId(13);
                }else if(headDescr.equals("bht")) {
                    channel.setChannelUserId(14);
                }else if(headDescr.equals("jxy")) {
                    channel.setChannelUserId(15);
                }else if(headDescr.equals("lin")) {
                    channel.setChannelUserId(16);
                }else if(headDescr.equals("hth")) {
                    channel.setChannelUserId(17);
                }else if(headDescr.equals("viptf")) {
                    channel.setChannelUserId(19);
                }

                if(serial == null) {
                    channel.setSerial(2);
                } else {
                    channel.setSerial(serial + 1);
                }

                String redirectUrl = redirectUrls.replaceAll(" ", "");
                if(redirectUrl.contains("?")) {
                    channel.setRedirectUrl(redirectUrl + "&channel=" + channelValue);
                } else {
                    channel.setRedirectUrl(redirectUrl + "?channel=" + channelValue);
                }

                channel.setShortUrl(shortUrl);

                // 执行增加操作
                channelDao.addChannel(channel);
                int pid=channel.getId();
                // 同步channel_old信息
                channel.setChannel(channelValue + "-old");
                channel.setPid(pid);
                channel.setChannelUserId(null);
                channel.setDataUserId(null);
                channel.setCoupon(null);
                channelDao.addChannel(channel);
                try {
                    if(!StringUtils.isEmpty(domain)){
                        Admin admin = UserUtil.getAdmin();
                        Map<String,String> map = new HashMap<>();
                        map.put("url",channel.getRedirectUrl());
                        map.put("adminName",admin.getName());
                        map.put("domain",domain);
                        if (shopId.contains("GUOB")){
                            map.put("title","XXXX");
                        } else if (shopId.contains("JUMD")){
                            map.put("title","XXX");
                        } else if (shopId.contains("YQKJ")){
                            map.put("title","易全");
                        } else if (shopId.contains("YGYX")){
                            map.put("title","XXX");
                        } else if (shopId.contains("ZXLP")){
                            map.put("title","益惠严选");
                        } else if (shopId.contains("YXHD")){
                            map.put("title","优享好兑");
                        } else if (shopId.contains("JCYX005")){
                            map.put("title","进程严选");
                        } else {
                            map.put("title","");
                        }
                        guchuangRabbitTemplate.convertAndSend(QueueConstants.CHANNEL_ADD_QUEUE, JSON.toJSONString(map));
                    }
                } catch (AmqpException e) {
                    log.error("自动创建渠道域名出错==>",e);
                }
            }
        }
    }

    // 手动生成渠道
    public void getManualChannel(String platform, String channel, String redirectUrl, String shortUrl,Integer dataUserId, BigDecimal coupon) {
        // 判断渠道是否存在
        if(StringUtils.isEmpty(channel)) {
            throw new ApiException("渠道不能为空！");
        } else {
            // 验证是否存在该渠道数据
            if (channelDao.isExist(channel) > 0) {
                throw new ApiException("该渠道已存在，请勿重复添加！");
            }
        }

        Channel c = new Channel();
        // 执行增加操作
        c.setPid(0);
        c.setPlatform(platform);
        c.setChannel(channel);
        c.setSort(1);
        c.setCreateTime(new Date());
        c.setDataUserId(dataUserId);
        c.setCoupon(coupon);
        redirectUrl = redirectUrl.replaceAll(" ", "");
        if(redirectUrl.contains("?")) {
            c.setRedirectUrl(redirectUrl + "&channel=" + channel);
        } else {
            c.setRedirectUrl(redirectUrl + "?channel=" + channel);
        }
        c.setShortUrl(shortUrl);
        c.setSerial(this.getSerial(channel));
        c.setChannelUserId(null);
        if(channel.startsWith("wei-sms")) {
            c.setChannelUserId(4);
        }else if(channel.startsWith("ygyx-sms")||channel.startsWith("txg-sms")) {
            c.setChannelUserId(7);
        }else if(channel.startsWith("jx-sms")) {
            c.setChannelUserId(12);
        }else if(channel.startsWith("ht-sms")) {
            c.setChannelUserId(13);
        }else if(channel.startsWith("bht-sms")) {
            c.setChannelUserId(14);
        }else if(channel.startsWith("jxy-sms")) {
            c.setChannelUserId(15);
        }else if(channel.startsWith("lin-sms")) {
            c.setChannelUserId(16);
        }else if(channel.startsWith("hth-sms")) {
            c.setChannelUserId(17);
        }else if(channel.startsWith("viptf-sms")) {
            c.setChannelUserId(19);
        }
        channelDao.addChannel(c);

        int pid=c.getId();
        // 同步channel_old信息
        c.setChannel(channel + "-old");
        c.setPid(pid);
        c.setChannelUserId(null);
        c.setDataUserId(null);
        c.setCoupon(null);
        channelDao.addChannel(c);
    }

    // 获取渠道序号
    public Integer getSerial(String channel) {
        int index = channel.lastIndexOf("-");
         return Integer.valueOf(channel.substring(index + 1, channel.length()));
    }

    @Override
    public Integer updateChannel(ChannelRequest channelRequest) {
        return channelDao.updateChannel(channelRequest);
    }

    @Override
    public List<Channel> getChannelByPlat(String platform) {
        return channelDao.getChannelByPlat(platform);
    }

    @Override
    public List<Channel> getChannelByPlatform(String platform) {
        return channelDao.getChannelByPlat(platform);
    }

    @Override
    public Channel getChannelInfoByChannel(String channel) {
        return channelDao.getChannelInfoByChannel(channel);
    }

    @Override
    public void removeData(Integer id) {
        channelDao.removeData(id);
    }

    @Override
    public void removeMoreData(Integer[] ids) {
        if(ids.length > 0) {
            for(Integer id : ids) {
                channelDao.removeData(id);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertPromotePlat(ChannelRequest channelRequest) {
        Channel channel = new Channel();
        // 默认平台 h5
        channel.setPlatform("h5");
        channel.setSort(1);
        if(channelRequest.getPromotePlat().length > 0) {
            for (String chan : channelRequest.getPromotePlat()) {
                // 渠道 = 推广方 + 推广平台 + 序号
                String channelHead = channelRequest.getPromoters() + "-" + chan;
                Integer serial = channelDao.getSerial(channelHead);
                String channelName = "";
                if(serial == null) {
                    channelName = channelHead + "-" + "01";
                } else {
                    if(serial < 10) {
                        channelName = channelHead + "-" + "0" + serial;
                    } else {
                        channelName = channelHead + "-" + serial;
                    }
                }
                channel.setChannel(channelName);
                // 排序
                channel.setSort(null);
                // 渠道描述 = 推广方 + 推广平台
                String promoters = channelRequest.getPromoters();
                String headDescr = Optional.ofNullable(PromotersEnums.getName(promoters)).orElse(promoters);
                channel.setChannelDesc(headDescr + " - " + PromotePlatformEnums.getName(chan));
                // 跳转url = 商品id + 渠道
                SelectExam selectExam = selectExamDao.findById(channelRequest.getSelectExamId());
                String redirectUrl = "https://sale.quanminyanxuan.com/pages/productDetail/hotProductDetail?pId=" + selectExam.getProductId() + "&channel=" + channelName;
                channel.setRedirectUrl(redirectUrl);

                // 索引
                if(serial == null) {
                    channel.setSerial(2);
                } else {
                    channel.setSerial(serial + 1);
                }
                channel.setDataUserId(channelRequest.getDataUserId());
                // 渠道--执行增加操作
                channelDao.insertPromoteChannel(channel);

                // 选品渠道--执行增加操作
                selectChannelDao.insertSelChannel(channelRequest.getSelectExamId(), channel.getId());

                int pid=channel.getId();
                // 同步channel_old信息
                channel.setChannel(channelName + "-old");
                channel.setPid(pid);
                channel.setChannelUserId(null);
                channel.setDataUserId(null);
                channel.setCreateTime(new Date());
                channelDao.insertChannel(channel);
            }
        }
    }

    @Override
    public Integer inChannelParam(Integer id, String channelParam) {
        return channelDao.inChannelParam(id, channelParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChannelStatus(Integer channelId, String channelStatus) {
        channelDao.updateChannelStatus(channelId, channelStatus);
    }

    @Override
    public List<Channel> getChannels() {
        String channel = null;
        String userId= UserUtil.getPrincipal();
        Admin admin = adminService.getAdminByEmail(userId);
        if (admin!=null && admin.getId().equals(adminIdjxy)){
            channel = "jxy-tt";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(userId) && "csb001@lc.com".equals(userId)){
            channel = "qw-";
        }
        return channelDao.getChannels(channel);
    }

    /*public static void main(String[] args) {
        String str = "TEST-ZERO-05";
        String target = str.substring(str.lastIndexOf("-") + 1);
        Integer num = Integer.parseInt(target) + 1;
        String number = "";
        if(num < 10) {
            number = "0" + num;
        } else {
            number = num.toString();
        }
        // System.out.println(number);
    }*/


}
